package pers.kw.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@RestController
public class ApiController {

    @RequestMapping(value = "/ec/app/index")
    public String index() {
        return "这里是前端EC APP";
    }

    @Value("${kw.sso.client-id:}")
    private String clientId;

    @Value("${kw.sso.client-secret:}")
    private String clientSecret;

    @Value("${kw.sso.redirect-uri:}")
    private String redirectUri;

    @Value("${kw.sso.access-token-uri:}")
    private String accessTokenUri;

    @GetMapping("/token/{code}")
    public Map tokenInfo(@PathVariable String code) throws UnsupportedEncodingException {
        //获取token
        return this.getAccessToken(code);
    }

    /**
     * 获取token
     */
    public Map getAccessToken(String code) throws UnsupportedEncodingException {
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        byte[] authorization = (clientId + ":" + clientSecret).getBytes(StandardCharsets.UTF_8);
        String base64Auth = Base64Utils.encodeToString(authorization);
        headers.add("Authorization", "Basic " + base64Auth);

        MultiValueMap<String, String> param = new LinkedMultiValueMap<>();
        param.add("code", code);
        param.add("grant_type", "authorization_code");
        param.add("redirect_uri", redirectUri);
        param.add("scope", "all");
        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(param, headers);
        ResponseEntity<Map> response = restTemplate.postForEntity(accessTokenUri, request, Map.class);
        return response.getBody();
    }
}
